using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System.IO;

namespace EntityKit.Editor
{
    public class PrefabTemplateManager : EditorWindow
    {
        private Vector2 m_ScrollPosition;
        private List<EntityTemplateInfo> m_Templates = new List<EntityTemplateInfo>();
        private string m_SearchFilter = "";
        private string m_NewTemplateName = "";
        private GameObject m_TemplateSourceObject;
        private string m_TemplatePath = "Assets/Templates";
        private GUIStyle m_HeaderStyle;
        private GUIStyle m_BoxStyle;
        private GUIStyle m_TemplateBoxStyle;
        private GUIStyle m_ButtonStyle;
        private bool m_StylesInitialized = false;
        private bool m_ShowCreatePanel = false;
        
        private class EntityTemplateInfo
        {
            public string Name;
            public string Path;
            public Object Asset;
            public System.DateTime LastModified;
        }


        public static void ShowWindow()
        {
            var window = GetWindow<PrefabTemplateManager>("实体模板管理");
            window.minSize = new Vector2(500, 400);
            window.Show();
        }

        private void OnGUI()
        {
            InitializeStyles();
            DrawHeader();
            DrawToolBar();
            
            if (m_ShowCreatePanel)
            {
                DrawCreatePanel();
                GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1));
            }
            
            DrawTemplatesList();
        }

        private void InitializeStyles()
        {
            if (m_StylesInitialized) return;

            m_HeaderStyle = new GUIStyle(EditorStyles.largeLabel);
            m_HeaderStyle.fontStyle = FontStyle.Bold;
            m_HeaderStyle.fontSize = 16;
            m_HeaderStyle.alignment = TextAnchor.MiddleCenter;

            m_BoxStyle = new GUIStyle(EditorStyles.helpBox);
            m_BoxStyle.padding = new RectOffset(10, 10, 10, 10);
            m_BoxStyle.margin = new RectOffset(5, 5, 5, 5);

            m_TemplateBoxStyle = new GUIStyle(EditorStyles.helpBox);
            m_TemplateBoxStyle.padding = new RectOffset(10, 10, 10, 10);
            m_TemplateBoxStyle.margin = new RectOffset(10, 10, 5, 5);

            m_ButtonStyle = new GUIStyle(GUI.skin.button);
            m_ButtonStyle.padding = new RectOffset(10, 10, 5, 5);
            m_ButtonStyle.margin = new RectOffset(5, 5, 5, 5);

            m_StylesInitialized = true;
        }

        private void DrawHeader()
        {
            GUILayout.Space(10);
            GUILayout.Label("实体模板管理器", m_HeaderStyle);
            GUILayout.Space(5);
            
            EditorGUILayout.HelpBox("管理项目中的实体模板，可以创建、编辑和删除实体模板。", MessageType.Info);
            
            GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1));
        }

        private void DrawToolBar()
        {
            EditorGUILayout.BeginHorizontal();
            
            m_SearchFilter = EditorGUILayout.TextField("搜索:", m_SearchFilter, GUILayout.ExpandWidth(true));
            
            if (GUILayout.Button(m_ShowCreatePanel ? "取消创建" : "创建模板", GUILayout.Width(100), GUILayout.Height(20)))
            {
                m_ShowCreatePanel = !m_ShowCreatePanel;
                if (!m_ShowCreatePanel)
                {
                    m_NewTemplateName = "";
                    m_TemplateSourceObject = null;
                }
            }
            
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.Space();
        }

        private void DrawCreatePanel()
        {
            EditorGUILayout.BeginVertical(m_BoxStyle);
            EditorGUILayout.LabelField("创建新模板", EditorStyles.boldLabel);
            
            m_NewTemplateName = EditorGUILayout.TextField("模板名称:", m_NewTemplateName);
            m_TemplateSourceObject = (GameObject)EditorGUILayout.ObjectField("源对象:", m_TemplateSourceObject, typeof(GameObject), true);
            m_TemplatePath = EditorGUILayout.TextField("保存路径:", m_TemplatePath);
            
            EditorGUILayout.Space();
            
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("创建", m_ButtonStyle))
            {
                CreateTemplate();
            }
            
            if (GUILayout.Button("选择路径", m_ButtonStyle))
            {
                string selectedPath = EditorUtility.OpenFolderPanel("选择模板保存路径", "Assets", "");
                if (!string.IsNullOrEmpty(selectedPath))
                {
                    if (selectedPath.StartsWith(Application.dataPath))
                    {
                        m_TemplatePath = "Assets" + selectedPath.Substring(Application.dataPath.Length);
                    }
                    else
                    {
                        EditorUtility.DisplayDialog("错误", "请选择项目Assets文件夹内的路径", "确定");
                    }
                }
            }
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.EndVertical();
            EditorGUILayout.Space();
        }

        private void DrawTemplatesList()
        {
            LoadTemplates();
            
            EditorGUILayout.LabelField($"模板数量: {m_Templates.Count}", EditorStyles.boldLabel);
            EditorGUILayout.Space();
            
            m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);
            
            if (m_Templates.Count == 0)
            {
                GUILayout.FlexibleSpace();
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                var emptyStyle = new GUIStyle(EditorStyles.label);
                emptyStyle.alignment = TextAnchor.MiddleCenter;
                emptyStyle.normal.textColor = EditorGUIUtility.isProSkin ? 
                    new Color(0.7f, 0.7f, 0.7f) : 
                    new Color(0.4f, 0.4f, 0.4f);
                GUILayout.Label("未找到模板。点击\"创建模板\"按钮创建新模板。", emptyStyle);
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
                GUILayout.FlexibleSpace();
            }
            else
            {
                foreach (var template in m_Templates)
                {
                    if (string.IsNullOrEmpty(m_SearchFilter) || 
                        template.Name.ToLower().Contains(m_SearchFilter.ToLower()))
                    {
                        DrawTemplateItem(template);
                    }
                }
            }
            
            EditorGUILayout.EndScrollView();
        }

        private void DrawTemplateItem(EntityTemplateInfo template)
        {
            EditorGUILayout.BeginVertical(m_TemplateBoxStyle);
            
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(template.Name, EditorStyles.boldLabel);
            GUILayout.FlexibleSpace();
            EditorGUILayout.LabelField($"修改时间: {template.LastModified:yyyy-MM-dd HH:mm}", GUILayout.Width(150));
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.ObjectField("模板:", template.Asset, typeof(Object), false);
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.TextField("路径:", template.Path);
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.Space();
            
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("实例化", m_ButtonStyle))
            {
                InstantiateTemplate(template);
            }
            
            if (GUILayout.Button("在Project窗口中显示", m_ButtonStyle))
            {
                EditorGUIUtility.PingObject(template.Asset);
            }
            
            if (GUILayout.Button("删除", m_ButtonStyle))
            {
                DeleteTemplate(template);
            }
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.EndVertical();
            EditorGUILayout.Space();
        }

        private void LoadTemplates()
        {
            m_Templates.Clear();
            
            // 查找所有Prefab文件作为模板
            string[] guids = AssetDatabase.FindAssets("t:Prefab", new[] { "Assets" });
            
            foreach (string guid in guids)
            {
                string assetPath = AssetDatabase.GUIDToAssetPath(guid);
                Object asset = AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject));
                
                if (asset != null)
                {
                    EntityTemplateInfo info = new EntityTemplateInfo
                    {
                        Name = Path.GetFileNameWithoutExtension(assetPath),
                        Path = assetPath,
                        Asset = asset,
                        LastModified = File.GetLastWriteTime(assetPath)
                    };
                    
                    m_Templates.Add(info);
                }
            }
        }

        private void CreateTemplate()
        {
            if (string.IsNullOrEmpty(m_NewTemplateName))
            {
                EditorUtility.DisplayDialog("错误", "请输入模板名称", "确定");
                return;
            }
            
            if (m_TemplateSourceObject == null)
            {
                EditorUtility.DisplayDialog("错误", "请选择源对象", "确定");
                return;
            }
            
            if (!Directory.Exists(m_TemplatePath))
            {
                Directory.CreateDirectory(m_TemplatePath);
            }
            
            string fullPath = Path.Combine(m_TemplatePath, m_NewTemplateName + ".prefab");
            
            // 创建Prefab
            PrefabUtility.SaveAsPrefabAsset(m_TemplateSourceObject, fullPath);
            
            // 刷新资源数据库
            AssetDatabase.Refresh();
            
            // 重置创建面板
            m_NewTemplateName = "";
            m_TemplateSourceObject = null;
            m_ShowCreatePanel = false;
            
            EditorUtility.DisplayDialog("成功", "模板创建成功", "确定");
            Repaint();
        }

        private void InstantiateTemplate(EntityTemplateInfo template)
        {
            if (template.Asset != null)
            {
                GameObject instance = PrefabUtility.InstantiatePrefab(template.Asset) as GameObject;
                if (instance != null)
                {
                    // 将实例放置在场景中心或当前选择对象附近
                    if (Selection.activeGameObject != null)
                    {
                        instance.transform.position = Selection.activeGameObject.transform.position + Vector3.one;
                    }
                    else
                    {
                        instance.transform.position = Vector3.zero;
                    }
                    
                    Selection.activeGameObject = instance;
                }
            }
        }

        private void DeleteTemplate(EntityTemplateInfo template)
        {
            if (EditorUtility.DisplayDialog("确认删除", 
                $"确定要删除模板 '{template.Name}' 吗？此操作不可撤销。", 
                "删除", "取消"))
            {
                AssetDatabase.DeleteAsset(template.Path);
                AssetDatabase.Refresh();
                Repaint();
            }
        }
    }
}